"use client";

import React, { useEffect, useRef, useState, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { useGame } from "@/hooks/use-game";
import { GAME_CONFIG } from "@/lib/game-config";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { ModeToggle } from "@/components/mode-toggle";
import { Trophy, Play, RotateCcw } from "lucide-react";

export default function BirdGame() {
  const { gameState, jump, startGame } = useGame();
  const gameContainerRef = useRef<HTMLDivElement>(null);
  const [debugInfo, setDebugInfo] = useState<string[]>([]);
  
  // 添加调试信息
  const addDebugInfo = useCallback((info: string) => {
    setDebugInfo(prev => {
      const newInfo = [...prev, `${new Date().toLocaleTimeString()}: ${info}`];
      // 只保留最新的10条信息
      return newInfo.slice(-10);
    });
  }, []);

  // 处理点击/触摸事件
  const handleInteraction = (e: React.MouseEvent | React.TouchEvent) => {
    e.preventDefault();
    addDebugInfo("触发点击/触摸事件");
    console.log("触发点击/触摸事件");
    
    // 直接在这里检查游戏状态
    console.log("当前游戏状态:", gameState.state);
    console.log("当前鸟的位置:", gameState.bird.y);
    console.log("当前鸟的速度:", gameState.bird.velocity);
    
    // 调用jump并立即记录
    jump();
    addDebugInfo("jump()已调用");
    
    // 延迟检查状态变化
    setTimeout(() => {
      console.log("jump后游戏状态:", gameState.state);
      console.log("jump后鸟的速度:", gameState.bird.velocity);
      addDebugInfo(`jump后速度: ${gameState.bird.velocity}`);
    }, 100);
  };

  // 处理键盘事件
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.code === "Space" || e.key === " " || e.key === "ArrowUp") {
        e.preventDefault();
        addDebugInfo(`触发键盘事件: ${e.key}`);
        console.log("触发键盘事件:", e.key);
        
        // 直接在这里检查游戏状态
        console.log("键盘事件 - 当前游戏状态:", gameState.state);
        console.log("键盘事件 - 当前鸟的位置:", gameState.bird.y);
        console.log("键盘事件 - 当前鸟的速度:", gameState.bird.velocity);
        
        // 调用jump并立即记录
        jump();
        addDebugInfo("键盘事件 - jump()已调用");
        
        // 延迟检查状态变化
        setTimeout(() => {
          console.log("键盘事件 - jump后游戏状态:", gameState.state);
          console.log("键盘事件 - jump后鸟的速度:", gameState.bird.velocity);
          addDebugInfo(`键盘事件 - jump后速度: ${gameState.bird.velocity}`);
        }, 100);
      }
    };

    addDebugInfo("添加键盘事件监听器");
    console.log("添加键盘事件监听器");
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [jump, addDebugInfo]);
  
  // 监听游戏状态变化
  useEffect(() => {
    addDebugInfo(`游戏状态变化: ${gameState.state}`);
  }, [gameState.state, addDebugInfo]);

  // 游戏区域样式
  const gameAreaStyle: React.CSSProperties = {
    width: `${GAME_CONFIG.GAME_WIDTH}px`,
    height: `${GAME_CONFIG.GAME_HEIGHT}px`,
    position: "relative",
    overflow: "hidden",
    backgroundColor: "hsl(var(--sky))",
    borderRadius: "12px",
    boxShadow: "0 10px 30px rgba(0, 0, 0, 0.2)",
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-screen p-4 bg-gradient-to-b from-background to-secondary/20">
      <div className="flex justify-between items-center w-full max-w-md mb-4">
        <h1 className="text-3xl font-bold text-primary">飞鸟游戏</h1>
        <ModeToggle />
      </div>

      <div
        ref={gameContainerRef}
        className="game-container touch-none select-none"
        style={gameAreaStyle}
        onClick={handleInteraction}
        onTouchStart={handleInteraction}
        onMouseDown={handleInteraction} // 添加鼠标按下事件
        tabIndex={0} // 使div可聚焦，以便捕获键盘事件
        onKeyDown={(e) => {
          if (e.code === "Space" || e.key === " " || e.key === "ArrowUp") {
            e.preventDefault();
            console.log("组件内键盘事件触发");
            addDebugInfo("组件内键盘事件触发");
            jump();
          }
        }}
        // 确保组件加载后自动获取焦点
        onFocus={() => addDebugInfo("游戏区域获得焦点")}
        onBlur={() => addDebugInfo("游戏区域失去焦点")}
      >
        {/* 云朵背景 */}
        <div className="absolute inset-0 overflow-hidden">
          <div className="parallax-bg absolute top-[10%] left-[10%] w-16 h-8 bg-white/70 rounded-full" />
          <div className="parallax-bg absolute top-[20%] left-[70%] w-20 h-10 bg-white/70 rounded-full" />
          <div className="parallax-bg absolute top-[40%] left-[30%] w-24 h-12 bg-white/80 rounded-full" />
        </div>

        {/* 鸟 - 恢复正常大小和位置 */}
        <div
          className={`absolute left-1/2 z-10`}
          style={{
            width: `${GAME_CONFIG.BIRD_WIDTH}px`,
            height: `${GAME_CONFIG.BIRD_HEIGHT}px`,
            transform: `translateX(-${GAME_CONFIG.BIRD_WIDTH / 2}px) translateY(${gameState.bird.y}px) rotate(${gameState.bird.rotation}deg)`,
            transformOrigin: "center",
            backgroundColor: gameState.bird.velocity < 0 ? "#ff6600" : "#ffcc00", // 跳跃时变色
            borderRadius: "50% 50% 40% 40%",
            border: "2px solid black",
          }}
        >
          {/* 简化的鸟眼睛 */}
          <div 
            style={{
              position: "absolute",
              top: "8px",
              right: "8px",
              width: "8px",
              height: "8px",
              backgroundColor: "white",
              borderRadius: "50%",
              border: "2px solid black"
            }}
          />
          
          {/* 简化的鸟嘴 */}
          <div 
            style={{
              position: "absolute",
              top: "15px",
              right: "0",
              width: "10px",
              height: "6px",
              backgroundColor: "orange",
              borderRadius: "0 50% 50% 0",
              border: "1px solid black"
            }}
          />
        </div>

        {/* 管道 */}
        {gameState.pipes.map((pipe) => (
          <React.Fragment key={pipe.id}>
            {/* 上管道 */}
            <div
              className="pipe absolute"
              style={{
                width: `${GAME_CONFIG.PIPE_WIDTH}px`,
                height: `${pipe.topHeight}px`,
                left: `${pipe.x}px`,
                top: 0,
                backgroundColor: "hsl(var(--pipe))",
                borderBottomLeftRadius: "4px",
                borderBottomRightRadius: "4px",
                borderBottom: "4px solid hsl(var(--pipe)/80%)",
                borderLeft: "4px solid hsl(var(--pipe)/90%)",
                borderRight: "4px solid hsl(var(--pipe)/70%)",
              }}
            />
            {/* 下管道 */}
            <div
              className="pipe absolute"
              style={{
                width: `${GAME_CONFIG.PIPE_WIDTH}px`,
                height: `${
                  GAME_CONFIG.GAME_HEIGHT -
                  pipe.topHeight -
                  GAME_CONFIG.PIPE_GAP -
                  GAME_CONFIG.GROUND_HEIGHT
                }px`,
                left: `${pipe.x}px`,
                top: `${pipe.topHeight + GAME_CONFIG.PIPE_GAP}px`,
                backgroundColor: "hsl(var(--pipe))",
                borderTopLeftRadius: "4px",
                borderTopRightRadius: "4px",
                borderTop: "4px solid hsl(var(--pipe)/80%)",
                borderLeft: "4px solid hsl(var(--pipe)/90%)",
                borderRight: "4px solid hsl(var(--pipe)/70%)",
              }}
            />
          </React.Fragment>
        ))}

        {/* 地面 */}
        <div
          className="absolute bottom-0 w-full"
          style={{
            height: `${GAME_CONFIG.GROUND_HEIGHT}px`,
            backgroundColor: "hsl(var(--ground))",
            borderTop: "4px solid hsl(var(--ground)/80%)",
            backgroundImage:
              "repeating-linear-gradient(45deg, hsl(var(--ground)/90%) 0px, hsl(var(--ground)/90%) 10px, hsl(var(--ground)) 10px, hsl(var(--ground)) 20px)",
          }}
        />

        {/* 分数显示 */}
        <div className="absolute top-4 left-0 right-0 text-center">
          <div className="text-4xl font-bold text-white drop-shadow-md">
            {gameState.score}
          </div>
        </div>

        {/* 游戏状态UI */}
        <AnimatePresence>
          {gameState.state === GAME_CONFIG.GAME_STATES.READY && (
            <motion.div
              className="absolute inset-0 flex flex-col items-center justify-center bg-black/30 backdrop-blur-sm z-20"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
            >
              <Card className="p-6 max-w-[80%] text-center bg-background/90">
                <h2 className="text-2xl font-bold mb-4">飞鸟游戏</h2>
                <p className="mb-6">点击屏幕或按空格键让小鸟飞翔</p>
                <Button
                  onClick={(e) => {
                    e.stopPropagation();
                    console.log("开始游戏按钮被点击");
                    addDebugInfo("开始游戏按钮被点击");
                    // 直接调用jump而不是startGame，因为jump会在READY状态下调用startGame
                    jump();
                  }}
                  className="w-full"
                  onMouseDown={(e) => e.stopPropagation()}
                  onTouchStart={(e) => e.stopPropagation()}
                >
                  <Play className="mr-2 h-4 w-4" /> 开始游戏
                </Button>
              </Card>
            </motion.div>
          )}

          {gameState.state === GAME_CONFIG.GAME_STATES.GAME_OVER && (
            <motion.div
              className="absolute inset-0 flex flex-col items-center justify-center bg-black/30 backdrop-blur-sm z-20"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
            >
              <Card className="p-6 max-w-[80%] text-center bg-background/90">
                <h2 className="text-2xl font-bold mb-2">游戏结束</h2>
                <div className="flex justify-center items-center gap-2 mb-4">
                  <Trophy className="text-yellow-500 h-5 w-5" />
                  <p className="text-lg">
                    得分: <span className="font-bold">{gameState.score}</span>
                  </p>
                </div>
                <p className="mb-6">
                  最高分:{" "}
                  <span className="font-bold">{gameState.highScore}</span>
                </p>
                <Button
                  onClick={(e) => {
                    e.stopPropagation();
                    console.log("再玩一次按钮被点击");
                    addDebugInfo("再玩一次按钮被点击");
                    // 直接调用jump而不是startGame
                    jump();
                  }}
                  className="w-full"
                  onMouseDown={(e) => e.stopPropagation()}
                  onTouchStart={(e) => e.stopPropagation()}
                >
                  <RotateCcw className="mr-2 h-4 w-4" /> 再玩一次
                </Button>
              </Card>
            </motion.div>
          )}
        </AnimatePresence>

        {/* 游戏提示 */}
        {gameState.state === GAME_CONFIG.GAME_STATES.PLAYING && (
          <div className="absolute bottom-[100px] left-0 right-0 text-center pointer-events-none">
            <p className="text-white text-sm opacity-70 drop-shadow-md">
              点击或按空格键跳跃
            </p>
          </div>
        )}
      </div>

      {/* 游戏说明 */}
      <div className="mt-6 text-center max-w-md text-sm text-muted-foreground">
        <p>
          通过点击屏幕或按空格键让小鸟飞翔，避开管道获得高分。每通过一个管道得1分。
        </p>
      </div>
      
      {/* 调试信息面板 */}
      <div className="debug-box">
        <div className="font-bold mb-1">调试信息:</div>
        <div>游戏状态: {gameState.state}</div>
        <div>鸟Y坐标: {Math.round(gameState.bird.y)}</div>
        <div>鸟速度: {Math.round(gameState.bird.velocity)}</div>
        <div>管道数量: {gameState.pipes.length}</div>
        <div className="mt-2 border-t border-white/30 pt-1">
          <div className="font-bold">事件日志:</div>
          {debugInfo.map((info, index) => (
            <div key={index} className="text-xs">{info}</div>
          ))}
        </div>
      </div>
    </div>
  );
}